package com.example.demo.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.bean.CmsCategory;
import com.example.demo.common.Response;
import com.example.demo.service.CmsCategoryService;

import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/category")
public class CmsCategoryController {
	
	@Autowired(required = false)
	private CmsCategoryService cmsCategoryService;
	
	@ApiOperation(value = "获取所有栏目信息" , notes = "从数据库检索所有信息并返回")
	@GetMapping("/selectall")
	public Response<List<CmsCategory>> quaryAll() {
		
		List<CmsCategory> cs =  cmsCategoryService.getAllCategories();
		return Response.ok(cs);
	}
	
	@ApiOperation(value = "保存或者更新栏目信息" ,notes = "如果传递参数时指明了栏目编号，那么执行更新操作<br/>"+
	"如果传递参数时没有指明栏目编号，那么执行插入操作")
	@PostMapping("/saveorupdate")
	public Response<String> saveOrUpdate(CmsCategory cmsCategory)
	{
		if (!cmsCategoryService.saveOrUpdateCmsCategory(cmsCategory)) {
			return Response.error("操作失败");
		}
		return Response.ok("操作成功");
	}
	
	@ApiOperation(value = "按照栏目编号，删除栏目信息!")
	@DeleteMapping("/deletebyid")
	public Response<String> deleteById(String id) {
		//调用业务方法
		int num = cmsCategoryService.deleteById(id);
		
		//根据处理结果返回不同的数据
		if (num==-1) {
			return Response.error("请先删除所有子栏目");
		}
		if(num==-2){
			return Response.error("请先删除该栏目下的所有文章");
		}
		if (num==0) {
			return Response.error("此栏目不存在");
		}
		return Response.ok("成功删除！！！");
	}
	
	@ApiOperation(value = "批量删除栏目信息!")
	@DeleteMapping("/deletebyids")
	public Response<String> deleteByIds(String[] ids) {
		String result = cmsCategoryService.batchDelete(ids);
		return Response.ok(result);
	}
	
}




